<template>
	<view>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :duration="0" :show="isOpen" @close="closeSearch" mode="top">
			<view id="popup" @touchmove.stop.prevent>
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="用户" v-if="!userStore.isSalesman">
							<uni-easyinput v-model="searchModel.nickName" placeholder="请输入用户" />
						</uni-forms-item>
						<uni-forms-item label="创建时间">
							<uni-datetime-picker type="date" placeholder="请选择创建时间" v-model="searchModel.recordTime"/>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
			</view>
		</up-popup>
		<view class="content">
			<view class="content-box" :style="{marginTop: `${marginTop}`}">
				<view class="operate main-flex">
					<view class="operate-item" v-if="isAdd && checkPermi(['zhouyz:salesmanPath:add']) && !checkRole(['admin'])">
						<up-button
							class="operate-btn main-flex"
							size="mini"
							type="primary"
							@click="add()">
							<uni-icons class="operate-btn-icon" type="location" size="28rpx" color="#ffffff"></uni-icons>
							<view class="operate-btn-text">打卡</view>
						</up-button>
					</view>
				</view>
				<!--地图-->
				<view class="map">
					<map
						:polyline="polyline"
						:markers="markers"
						:latitude="latitude"
						:longitude="longitude"
						style="width: 100%; height: 100%;">
					</map>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { computed, onMounted, ref, getCurrentInstance } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { salesmanPath } from "@/api/erp_api/sale"
import { isObjectEmptySimple, copyText, arrText, getNode, clusterData } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'

	const userStore = useUserStore()
	const { proxy } = getCurrentInstance()
	// 标题设置
	const title = ref('')
	const userId = ref('')
	const isAdd = ref(true)
	onLoad(async (option) => {
		if (option.userId) {
			userId.value = option.userId
			isAdd.value = userId.value == userStore.user.userId
		}
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	const marginTop = computed(() => {
		return isOpen.value ? '100vh' : 0
	})
	
	const latitude = ref('')
	const longitude = ref('')
	const getLocationFun = () => {
		// 获取当前位置
		uni.getLocation({
			type: 'gcj02',
			altitude: true,
			geocode: true,
			isHighAccuracy: true,
			success: function (res) {
				latitude.value = res.latitude
				longitude.value = res.longitude
			},
			fail(err) {
				console.log(err)
			}
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		nickName: '',
		lng: '',
		lat: '',
		recordTime: timeFormat()
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			nickName: '',
			lng: '',
			lat: '',
			recordTime: timeFormat()
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(1000)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 路线
	const polyline = ref([])
	const markers = ref([])
	
	// 表格头部
	const columns = ref([
		{ title: 'ID', key: 'id', width: '100rpx' },
		{ title: '用户ID', key: 'userId', width: '100rpx' },
		{ title: '经度', key: 'lng' },
		{ title: '纬度', key: 'lat' },
		{ title: '创建时间', key: 'recordTime' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.recordTime) {
			params.table = searchModel.value.recordTime
		}
		// 判断段当前用户
		if (searchModel.value.nickName) {
			params.nickName = searchModel.value.nickName
		} else if (userId.value) {
			params.userId = userId.value
		} else if (userStore.user.userId) {
			params.userId = userStore.user.userId
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanPath(params).then(res => {
			polyline.value = []
			markers.value = []
			tableList.value = res.rows || []
			const points = clusterData(tableList.value, 2)
			if (points.length > 0) {
				const groupList = polylineGroup(points)
				for(const item in groupList) {
					const pointsItem = groupList[item].map(item => {
							return {
								latitude: item.lat,
								longitude: item.lng
							}
						})
					polyline.value.push({
						points: pointsItem,
						color: '#1890ff',
						width: 2,
						dottedLine: true,
						arrowLine: true
					})
				}
				markers.value = points.map(item => {
					return {
						joinCluster: true,
						id: item.id,
						latitude: item.lat,
						longitude: item.lng,
						// #ifndef APP-IOS
						iconPath: '/static/images/locaton4.png',
						width: 48,
						height: 48,
						// #endif
						// #ifdef APP-IOS
						iconPath: '/static/images/locaton2.png',
						width: 20,
						height: 20,
						// #endif
						fontSize: 10,
						callout: {
							display: 'ALWAYS',
							content: `${item.nickName} : ${item.recordTime}`
						}
					}
				})
				
				latitude.value = markers.value[0].latitude
				longitude.value = markers.value[0].longitude
			} else {
				getLocationFun()
			}
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
			// uni.stopPullDownRefresh()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	const polylineGroup = (arr) => {
		return arr.reduce((acc, obj) => {
			const key = obj.userId
			if (!acc[key]) acc[key] = []
			acc[key].push(obj)
			return acc
		}, {})
	}
	
	//打卡
	const add = () => {
		uni.navigateTo({
			url: '/pages/sale/salesmanPathAdd'
		})
	}
	
	// 下拉刷新
	onPullDownRefresh(() => {
		getList()
	})
	
	onMounted(() => {
		searchFirst()
	})
</script>

<style scoped lang="scss">
.goods {
	align-items: flex-start;
	&_r {
		padding-left: 20rpx;
	}
}
.table-td-long1 {
	max-width: 180rpx;
}
.table-td-long {
	max-width: 200rpx;
}
.map {
	width: 100%;
	height: calc(100vh - 42px);
}
.content {
	height: 100vh;
	position: relative;
	overflow: hidden;
	&-box {
		// transition: all .3s;
	}
}
page, .content {
	background-color: #ffffff;
}
</style>
